<template>
  <div class="pic-uploader-component">
    <el-upload
      :disabled="disabled"
      :action="path + '/p/file/upload'"
      :headers="{ Authorization: token }"
      :show-file-list="false"
      :on-success="handleUploadSuccess"
      :before-upload="beforeAvatarUpload"
      style="width:100%;height:100%;"
    >
      <img v-if="resourcesVal" :src="resourcesVal" class="pic avatar" />
      <i v-else class="el-icon-plus pic-uploader-icon"></i>
    </el-upload>
  </div>
</template>

<script>
import Cookie from 'js-cookie'
import config from '../plugins/config'
export default {
  data () {
    return {
      resourcesVal: "",
      inited: false,
      path: config.path
    }
  },
  props: {
    value: {
      default: '',
      type: String
    },
    disabled: {
      default: false,
      type: Boolean
    },
    fullUrl: {
      default: false,
      type: Boolean
    }
  },
  watch: {
    value: function (newVal, oldVal) {
      if (!oldVal && newVal && !this.inited) {
        this.resourcesVal = newVal
        this.inited = true
      }
    }
  },
  computed: {
    token () {
      return 'bearer' + Cookie.get('token')
    }
  },
  methods: {
    // 图片上传
    handleUploadSuccess (response, file, fileList) {
      this.inited = true
      this.resourcesVal = file.response.resourcesUrl + file.response.filePath
      if (this.fullUrl) {
        this.$emit('input', this.resourcesVal)
      } else {
        this.$emit('input', file.response.filePath)
      }
    },
    // 限制图片上传大小
    beforeAvatarUpload (file) {
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error(this.$t('imageNoFormatUpload'))
        return false
      }

      // 判断图片类型来筛选图片格式上传
      let _type = file.type;
      if (_type.indexOf('png') == -1 && _type.indexOf('jpg') == -1 && _type.indexOf('jpeg') == -1) {
        this.$message.error(this.$t('imageSizeCannotExceed2MB'))
        return false
      }
      return
    }
  }
}
</script>

<style>
/* .pic-uploader-component .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
} */
.pic-uploader-component .el-upload {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
}
.pic-uploader-component .el-upload .pic {
  max-width: 100%;
  max-height: 100%;
}

.el-icon-plus {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

/* .pic-uploader-component .el-upload .pic-uploader-icon {
  font-size: 22px;
  color: #999;
  text-align: center;
} */
</style>
